/*
 * Copyright 2002-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.security.samples.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.samples.service.UserDetailService;

/**
 * @author Joe Grandja
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailService userDetailService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //表示下面的资源允许所有人访问
                .antMatchers("/css/**","/","/login").permitAll()
                .antMatchers("/**").authenticated()
                //表示下面路径下的所有资源只允许账号角色为user的人访问
                .antMatchers("/views/**").hasAnyRole("USER", "ADMIN")
                .antMatchers("/views/admin/**").hasRole("ADMIN")
                .antMatchers("/views/user/**").hasAnyRole("USER")
                .and()
                .formLogin()
                //访问除了/,/login,/css/**以为的地址都会转到/login的请求,跳转到login.jsp界面
                .loginPage("/login")
                //默认是/login,form提交的请求地址
                .loginProcessingUrl("/customLogin")
                .failureHandler(new CustomAuthenticationFailureHandler("/login"))
//                .successHandler(new SavedRequestAwareAuthenticationSuccessHandler())
                //认证成功后的跳转地址,如果alwaysUse为true,则表示不论在任何界面认证成功,都会跳转的defaultSuccessUrl
                //默认为false,若访问的是一个需认证的地址,那么改地址会被保存到session里,并跳转到认证界面.认证成功,
                // 跳转回session里保存的地址.session里只会保存最后一个触发认证的地址
                //SavedRequestAwareAuthenticationSuccessHandler这个类中说明一切
                //todo:此为重定向的跳转方式
                .defaultSuccessUrl("/success").and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login")
                .invalidateHttpSession(true);

        //todo:通过下面两行可以在任何位置获取到当前认证成功的用户信息
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        System.out.println(authentication.getName());
    }

//    /**
//     * 内存认证
//     *
//     * @param auth
//     * @throws Exception
//     */
//    @Autowired
//    public void configureGlobalMemory(AuthenticationManagerBuilder auth) throws Exception {
//        auth
//                .inMemoryAuthentication()
//                .withUser("user").password("password").roles("USER");
//    }

    /**
     * 自定义jdbc认证
     *
     * @param builder
     * @throws Exception
     */
    @Autowired
    public void configureGlobalDataSource(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(userDetailService);
    }

}
